import time
from utils.common_import import *
from utils.ext import inner_db
from .model import Framework, Image, RelationMap, Language, ImagesAddSchema, ImagesDeleteSchema,ImageGetScheme
from utils.ext import db_add_record, db_delete_record, db_update_record, \
                    db_query_record, db_transaction, db_add_record_if_not_exist

class PaiImagesMaintain(Resource):
    # @jwt_required()
    @request_arg_check(ImageGetScheme(), many=False, location="args")
    @exception_response()
    def get(self):
        images = db_query_record(Image)
        frameworks = db_query_record(Framework)
        languages = db_query_record(Language)
        relationship_maps = []
        # relationship_maps = db_query_record(RelationMap)
        page_index = 1
        per_page_items = 10
        if current_schema_instance:
            page_index = current_schema_instance["page_index"]
            per_page_items = current_schema_instance["per_page_items"]

        result = inner_db.session\
            .query(RelationMap)\
            .paginate(page_index,
                      per_page_items,
                      False)

        for item in result.items:
            relationship_maps.append(item.get_data_info())

        #镜像id转成镜像信息
        image_dict = {}
        for image in images:
            image_dict[str(image["id"])] = image
        logger.debug("image_dict is {}".format(image_dict))

        #语言id转成语言信息
        language_dict = {}
        for language in languages:
            language_dict[str(language["id"])] = language
        logger.debug("language_dict is {}".format(language_dict))

        #frameworkid 转换成框架信息
        framework_dict = {}
        for framework in frameworks:
            framework_dict[str(framework["id"])] = framework
        logger.debug("framework_dict is {}".format(framework_dict))

        #根据framework_id language_id 映射镜像
        relationship_info = {}
        for relationship in relationship_maps:
            try:
                framework_name = framework_dict[str(relationship["framework_id"])]["name"]
                language_name = language_dict[str(relationship["language_id"])]["name"]
                image_info = image_dict[str(relationship["image_id"])]
                relationship_info.setdefault((framework_name, language_name), [])
                relationship_info[(framework_name, language_name)].append(image_info)
            except Exception as err:
                logger.error(str(err))
        logger.debug("relationship_info is {}".format(relationship_info))

        images_map_info = []
        for relationship in relationship_info:
            images_map_info.append(dict(framework=relationship[0],
                                        language=relationship[1],
                                        images = relationship_info[relationship],
                                        total_page=result.pages))
        logger.debug("images_map_info is {}".format(images_map_info))

        return make_success_response(images_map_info)

    @jwt_required()
    @permission_auth("admin")
    @request_arg_check(ImagesAddSchema(), many=False)
    @exception_response()
    @db_transaction(inner_db.session)
    def post(self):
        image_name = current_schema_instance["image_name"]
        image_registry = current_schema_instance["image_registry"]
        framework = current_schema_instance["framework"]
        language = current_schema_instance["language"]
        provider = current_schema_instance.get("provider", "")

        image_path_info_raw = image_registry.split("/")
        image_domain = ""
        image_path = image_registry
        if len(image_path_info_raw) > 1:
            image_domain = "{}/".format(image_path_info_raw[0])
            image_path = "/".join(image_path_info_raw[1:])

        current_time = time.time()*1000
        #插入镜像若不存在
        db_add_record_if_not_exist(session= inner_db.session,
                      table_schema= Image,
                      filter_info= dict(domain=image_domain, path=image_path),
                      add_info= dict(name=image_name, path=image_path, domain=image_domain,
                                provider = provider, type=2, number = str(int(current_time)),
                                create_time=current_time, update_time=current_time))

        #插入Framework若不存在
        db_add_record_if_not_exist(session=inner_db.session,
                                   table_schema= Framework,
                                   filter_info=dict(name = framework),
                                   add_info= dict(name = framework,
                                                  create_time=current_time,
                                                  update_time=current_time))


        #插入Lang若不存在
        db_add_record_if_not_exist(session=inner_db.session,
                                   table_schema= Language,
                                   filter_info=dict(name = language),
                                   add_info= dict(name = language,
                                                  create_time=current_time,
                                                  update_time=current_time))
        try:
            inner_db.session.commit()
        except Exception as err:
            logger.info(err)
            return make_no_data_response(status=500, code=500, message=str(err))

        image_query =db_query_record(Image, filter_info=dict(number=str(int(current_time))))
        framework_quey = db_query_record(Framework, filter_info=dict(name = framework))
        language_query = db_query_record(Language, filter_info=dict(name = language))

        filter_info = dict(image_id = image_query[0]["id"],
                           framework_id = framework_quey[0]["id"],
                           language_id = language_query[0]["id"])

        add_info = dict(image_id = image_query[0]["id"],
                           framework_id = framework_quey[0]["id"],
                           language_id = language_query[0]["id"],
                           create_time=current_time,
                           update_time=current_time)

        db_add_record(session=inner_db.session,
                      table_schema=RelationMap,
                      filter_info=filter_info,
                      add_info=add_info)

        return make_no_data_response(status=200, code=0, message="success")

    @jwt_required()
    @permission_auth("admin")
    @request_arg_check(ImagesAddSchema(), many=False)
    @exception_response()
    @db_transaction(inner_db.session)
    def put(self):
        image_name = current_schema_instance["image_name"]
        image_registry = current_schema_instance["image_registry"]
        # framework = current_schema_instance.get("framework", "")
        # language = current_schema_instance.get("language", "")
        provider = current_schema_instance.get("provider", "")

        image_path_info_raw = image_registry.split("/")
        image_domain = ""
        image_path = image_registry
        if len(image_path_info_raw) > 1:
            image_domain = "{}/".format(image_path_info_raw[0])
            image_path = "/".join(image_path_info_raw[1:])

        current_time = time.time()*1000
        update_info = dict(name= image_name, image_path=image_path,
                                            image_domain = image_domain,
                                            update_time = current_time)
        if provider:
            update_info["provider"] = provider

        db_update_record(session= inner_db.session,
                         table_schema= Image,
                         filter_info= dict(domain=image_domain, path=image_path),
                         update_info= update_info)

        # 不支持修改映射关系
        # #插入Framework若不存在
        # if framework:
        #     db_add_record_if_not_exist(session=inner_db.session,
        #                                table_schema= Framework,
        #                                filter_info=dict(name = framework),
        #                                add_info= dict(name = framework,
        #                                               create_time=current_time,
        #                                               update_time=current_time))
        #
        #
        # #插入Lang若不存在
        # if language:
        #     db_add_record_if_not_exist(session=inner_db.session,
        #                                table_schema= Language,
        #                                filter_info=dict(name = language),
        #                                add_info= dict(name = language,
        #                                               create_time=current_time,
        #                                               update_time=current_time))

        return make_no_data_response(status=200, code=0, message="success")

    @jwt_required()
    @permission_auth("admin")
    @request_arg_check(ImagesDeleteSchema(), many=False)
    @exception_response()
    @db_transaction(inner_db.session)
    def delete(self):
        image_registry = current_schema_instance["image_registry"]
        image_path_info_raw = image_registry.split("/")

        image_domain = ""
        image_path = image_registry
        if len(image_path_info_raw) > 1:
            image_domain = "{}/".format(image_path_info_raw[0])
            image_path = "/".join(image_path_info_raw[1:])

        images = db_query_record(Image, dict(domain=image_domain, path=image_path))
        logger.info(images)

        for image in images:
            filter_info = dict(image_id = image["id"])
            if "framework" in current_schema_instance:
                filter_info["framework"] = current_schema_instance["framework"]
            if "language" in current_schema_instance:
                filter_info["language"] = current_schema_instance['language']

            db_delete_record(session= inner_db.session,
                            table_schema= RelationMap,
                            filter_info=filter_info)

        for image in images:
            relationship = db_query_record(RelationMap, dict(image_id = image["id"]))
            #删除后映射关系不存在则删除镜像表记录
            if not relationship:
                db_delete_record(session= inner_db.session,
                         table_schema= Image,
                         filter_info= dict(domain=image_domain, path=image_path))

        return make_no_data_response(status=200, code=0, message="success")
